package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.DroolsConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.opio.util.ExampleBase;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.GasDetection;
import com.ruoyi.system.domain.JobPlanBillDeclare;
import com.ruoyi.system.domain.SysPlan;
import com.ruoyi.system.domain.vo.SysGasPointVO;
import com.ruoyi.system.entity.SysGasPoint;
import com.ruoyi.system.entity.SysMonitor;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.SysGasPointService;
import com.ruoyi.system.service.SysMonitorService;
import com.ruoyi.system.service.SysRemindService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 可燃有毒气体点位(SysGasPoint)表服务实现类
 *
 * @author makejava
 * @since 2022-12-01 16:48:05
 */
@Slf4j
@Service("sysGasPointService")
public class SysGasPointServiceImpl implements SysGasPointService {
    @Resource
    private JobPlanBillDeclareMapper jobPlanBillDeclareDao;
    @Resource
    private SysGasPointMapper sysGasPointMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysPlanMapper sysPlanMapper;

    @Resource
    private SysMonitorService sysMonitorService;

    @Resource
    private KieContainer kieContainer;

    @Autowired
    private Configuration configuration;

    @Autowired
    private DroolsConfig droolsConfig;

    @Autowired
    private SysRemindService sysRemindService;
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;
    @Resource
    private SysUserMapper sysUserMapper;

    public static final String FileName = "/SysGasPoint.drl";

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysGasPoint queryById(Integer id) {
        return this.sysGasPointMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param sysGasPoint 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysGasPoint> queryByPage(SysGasPoint sysGasPoint) {
        return this.sysGasPointMapper.queryAllByLimit(sysGasPoint);
    }

    /**
     * 新增数据
     *
     * @param sysGasPoint 实例对象
     * @return 实例对象
     */
    @Override
    public SysGasPoint insert(SysGasPoint sysGasPoint) {
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey("qyzzts");
        List<SysUser> sysUsers = sysUserMapper.selectUserByRoleName(sysRole);
        if (!CollectionUtils.isEmpty(sysUsers)) {
            String stringBuffer = sysGasPoint.getInstallAddress() + "发生异常。";

            for (SysUser sys : sysUsers) {
                sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, sys.getUserId().intValue());
            }

            List<String> collect = sysUsers.stream().map(SysUser::getWxUserId).collect(Collectors.toList());
            EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
            sendMessageRequest.setTouser(CollUtil.join(collect, "|"));
            sendMessageRequest.setMsgtype("text");
            sendMessageRequest.setAgentid(1000319);
            EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
            messageContent.setContent(stringBuffer);
            sendMessageRequest.setText(messageContent);
            enterpriseWXService.pushMessage(sendMessageRequest);
        }

        this.sysGasPointMapper.insert(sysGasPoint);
        return sysGasPoint;
    }

    /**
     * 修改数据
     *
     * @param sysGasPoint 实例对象
     * @return 实例对象
     */
    @Override
    public SysGasPoint update(SysGasPoint sysGasPoint) {
        this.sysGasPointMapper.update(sysGasPoint);
        return this.queryById(sysGasPoint.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sysGasPointMapper.deleteById(id) > 0;
    }

    @Override
    public List<SysGasPoint> queryAll() {
        return sysGasPointMapper.queryAll();
    }

    @Override
    public List<SysGasPoint> testing(GasDetection gasDetection) {
        //1.根据票据号查询申报记录;
        JobPlanBillDeclare jobPlanBillDeclare = new JobPlanBillDeclare();
        jobPlanBillDeclare.setBillNumber(gasDetection.getJobNumber());
        List<JobPlanBillDeclare> jobPlanBillDeclares = jobPlanBillDeclareDao.queryAll(jobPlanBillDeclare);
        if (CollectionUtils.isEmpty(jobPlanBillDeclares)) {
            return new ArrayList<>();
        }

        //2.解析出所有气体点位ID;
        List<Integer> ids = new ArrayList<>();
        for (JobPlanBillDeclare values : jobPlanBillDeclares) {
            String gasLocal = values.getGasLocal();
            List<SysGasPoint> sysGasPoints = JSON.parseArray(gasLocal, SysGasPoint.class);
            if (!CollectionUtils.isEmpty(sysGasPoints)) {
                ids.addAll(sysGasPoints.stream().map(SysGasPoint::getId).collect(Collectors.toList()));
            }
        }

        log.info("解析出所有气体点位ID :{}", ids);
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }

        return sysGasPointMapper.testing(ids);
    }

    @Override
    public String importExcel(List<SysGasPoint> sysGasPoints, boolean updateSupport, String operName) {
        if (StringUtils.isNull(sysGasPoints) || sysGasPoints.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        for (SysGasPoint sysGasPoint : sysGasPoints) {
            // 根据部门名称获取部门ID
            String deptName = sysGasPoint.getDeptName();
            if (StringUtils.isNotEmpty(deptName)) {
                List<SysDept> sysDepts = sysDeptMapper.selectByDeptName(deptName);
                if (!CollectionUtils.isEmpty(sysDepts)) {
                    SysDept sysDept = sysDepts.get(0);
                    sysGasPoint.setDeptId(sysDept.getDeptId().intValue());
                }
            }
            // 根据处置方案名称获取处置方案ID
            String planName = sysGasPoint.getPlanName();
            if (StringUtils.isNotEmpty(planName)) {
                SysPlan sysPlan = sysPlanMapper.getByName(planName);
                if (sysPlan != null) {
                    sysGasPoint.setPlanId(sysPlan.getId());
                }
            }
        }
        sysGasPointMapper.insertBatch(sysGasPoints);
        return "成功";
    }

    @Override
    public void createDroolsFile() throws IOException, TemplateException {
        List<SysGasPointVO> date = getDate();
        Template template = configuration.getTemplate("SysGasPoint.ftl");
        Map<String, Object> map = new HashMap<>();
        map.put("SysGasPointVOList", date);
        FileOutputStream file = new FileOutputStream(droolsConfig.getUrl() + FileName);
        OutputStreamWriter out = new OutputStreamWriter(file, "utf-8");
        template.process(map, out);
        out.close();
        System.out.println("success");
        this.reload();
    }

    public List<SysGasPointVO> getDate() {
        List<SysGasPoint> sysGasPoints = sysGasPointMapper.queryAll();
        List<SysGasPointVO> sysGasPointVOS = new ArrayList<>();
        sysGasPoints.forEach(i -> {
            SysGasPointVO sysGasPointVO = new SysGasPointVO();
            BeanUtils.copyBeanProp(sysGasPointVO, i);
            // 低低报
            String playItLow = i.getPlayItLow();
            playItLow = StringUtils.isNotEmpty(playItLow) ? playItLow.replace("/", "") : playItLow;
            sysGasPointVO.setPlayItLow(StringUtils.isEmpty(playItLow) ? -1 : Double.valueOf(playItLow));
            // 低报
            String lowQuota = i.getLowQuota();
            lowQuota = StringUtils.isNotEmpty(lowQuota) ? lowQuota.replace("/", "") : lowQuota;
            sysGasPointVO.setLowQuota(StringUtils.isEmpty(lowQuota) ? -1 : Double.valueOf(lowQuota));
            // 高报
            String highQuota = i.getHighQuota();
            sysGasPointVO.setHighQuota(StringUtils.isEmpty(highQuota) ? -1 : Double.valueOf(highQuota));
            // 高高报
            String highAndMighty = i.getHighAndMighty();
            sysGasPointVO.setHighAndMighty(StringUtils.isEmpty(highAndMighty) ? -1 : Double.valueOf(highAndMighty));
            sysGasPointVO.setAlert(0);
            sysGasPointVOS.add(sysGasPointVO);
        });
        return sysGasPointVOS;
    }

    @Override
    public void reload() {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(FileUtil.readString(droolsConfig.getUrl() + FileName, Charset.forName("utf-8")), ResourceType.DRL);
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.ERROR)) {
            System.out.println(results.getMessages());
            throw new IllegalStateException("### errors ###");
        }
        kieContainer = kieHelper.getKieContainer();
        System.out.println("刷新文件");
    }

    // 定时查询实时数据，是否达到报警条件
    @Scheduled(cron = "0/60 * * * * ?")
    public void ScheduledDataAlert() {
        List<SysGasPointVO> date = getDate();
        Map<String, Object> map = ExampleBase.toResult();
        if (CollUtil.isNotEmpty(map)) {
            date.forEach(i -> {
                Object o = map.get(i.getDatabaseBitNumber());
                i.setAv(StringUtils.isEmpty(o.toString()) ? 0 : Double.valueOf(o.toString()));
                // 调用规则引擎判断
                KieSession kieSession = kieContainer.newKieSession();
                kieSession.insert(i);
                kieSession.fireAllRules();
                kieSession.dispose();
                if (i.getAlert() == 1) {
                    SysMonitor query = sysMonitorService.queryByDataBase(i.getDatabaseBitNumber());
                    if (query == null || !StringUtils.isEmpty(query.getMonitorEndTime()) || query.getMonitorState().equals("已超时")) {
                        SysMonitor sysMonitor = new SysMonitor();
                        sysMonitor.setMonitorType("可燃气体");
                        sysMonitor.setMonitorName(i.getInstallAddress());
                        sysMonitor.setRealTimeDataAddress(i.getDatabaseBitNumber());
                        sysMonitor.setMonitorParam("/");
                        sysMonitor.setMonitorLevel(i.getAlertType());
                        sysMonitor.setMonitorValue(i.getAv().toString());
                        sysMonitor.setMonitorConfirmState("未确认");
                        sysMonitor.setMonitorState("未恢复");
                        sysMonitor.setMonitorStartTime(DateUtil.now());
                        sysMonitorService.insert(sysMonitor);
                    }
                } else {
                    SysMonitor query = sysMonitorService.queryByDataBase(i.getDatabaseBitNumber());
                    if (query != null && StringUtils.isEmpty(query.getMonitorEndTime())) {
                        query.setMonitorEndTime(DateUtil.now());
                        query.setMonitorState("已恢复");
                        sysMonitorService.update(query);
                    }
                }
            });
        }
    }
}
